package br.com.imob.solr;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;

import br.com.imob.model.ImobItem;

public class SolrServiceImpl implements SolrService {

	private static final Logger log = Logger.getLogger(SolrServiceImpl.class);

	private SolrServer server;

	public void deleteAllItems() {

		try {
			server.deleteByQuery("*:*");
			server.commit();

		} catch (Exception e) {
			log.error(e.getMessage());
			log.error(">> Error deleting all items from Solr << ");
		}

	}

	public void addItem(ImobItem imobItem) {
		// TODO Auto-generated method stub

	}

	public ImobItem selectItemById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	public void addItems(List<ImobItem> items) {

		log.info("Adding " + items.size() + " items to Solr... ");

		try {
			server.addBeans(items);

			server.commit();

		} catch (Exception e) {
			log.error(e.getMessage());
			log.error(">> Error adding items in Solr << ");
		}

	}

	public List<ImobItem> selectItems(ImobItem criteria, Integer begin,
			Integer end) {

		try {
			
			SolrQuery solrQuery = new SolrQuery(buildQuery(criteria));

			solrQuery.addSort("priceImob", ORDER.asc);

			if (begin != null)
				solrQuery.setStart(begin);

			if (end != null)
				solrQuery.setRows(end);

			QueryResponse rsp = server.query(solrQuery);

			return rsp.getBeans(ImobItem.class);

		} catch (Exception e) {
			
			e.printStackTrace();
			log.error(">> Error querying items in Solr << ");
			return new ArrayList<ImobItem>();
		}
	}

	public Long totalFound(ImobItem criteria) {

		try {

			SolrQuery solrQuery = new SolrQuery(buildQuery(criteria));

			solrQuery.addSort("priceImob", ORDER.asc);

			QueryResponse rsp = server.query(solrQuery);

			return rsp.getResults().getNumFound();

		} catch (Exception e) {
			
			e.printStackTrace();
			log.error(">> Error querying items in Solr << ");
			return 0L;
		}

	}

	public String buildQuery(ImobItem criteria) {

		String query = "";

		if (criteria != null) {

			if (criteria.getNeighbor() != null)
				query = addAndClause(query,
						"neighbor:" + criteria.getNeighbor() );

			if (criteria.getGoal() != null)
				query = addAndClause(query, "goal:" + criteria.getGoal() );
		} else {
			query += "*:*";
		}

		return query;
	}

	public String addAndClause(String query, String q) {

		if ("".equals(query)) {
			query += q;
		} else {
			query += " AND " + q;
		}
		return query;
	}

	public String addOrClause(String query, String q) {

		if ("".equals(query)) {
			query += q;
		} else {
			query += " OR " + q;
		}
		return query;
	}

	public SolrServer getServer() {
		return server;
	}

	public void setServer(SolrServer server) {
		this.server = server;
	}

}
